var express = require('express');
var router = express.Router();
var sqlQuery = require('../../module/sql');


router.get('/', async(req, res, next)=>{
  let type = req.query.type

  let sqlStr7 = 'select * from film where state = 1 and Typeid = ?'
  let result7 = await sqlQuery(sqlStr7,[type])

  let sqlStr10 = 'select typeName from type where id = ?'
  let result10 = await sqlQuery(sqlStr10,[type])
  console.log(result10[0])

  //导航
  let Nav = await getNav()
  let typeList = await getType()
  let currentPage = Number.parseInt(req.query.page) || 1
  let sqlStr8 = "select count(id) as number from film where Typeid = ?"
   let result8 = await sqlQuery(sqlStr8,[type])
   let count = result8[0].number
   //总数  count
   //每页显示
   let pagesize = 18;
   //多少条也
   let page = Math.ceil(count/pagesize);
  //  let currentPage = 1; //当前页
   if(currentPage > page){
     currentPage = page;
   }
   let minItem = (currentPage * pagesize) - pagesize + 1;
   let maxItem = (currentPage * pagesize)

  //  console.log("总数",count,"-----","每页显示",pagesize,"-----","多少页",page,"-----",minItem,maxItem)
   let data=[]
   let film = result7
   let options1 = {film}
  //  console.log(options1)
   film.forEach((item,i) => {
     let itemNum = i +1;
     if(itemNum >= minItem && itemNum <= maxItem){
      //  console.log(item.id,item.filmName,i)
       data.push(item)
     }
   });
  //  return Array.from(data)
  //  console.log(data)
   const pages = {
    page,
    currentPage,
    hasPre:currentPage > 1, //上一页
    hasNext:currentPage < page //下一页
  }

  let options = {typeList,Nav,data,pages,result10,type}
  // console.log(data)
  // console.log(pages)
  res.render('home/type',options)
});


//获取导航
async function getNav(){
  let sqlStr = 'select * from nav where state = 1'
  let result = await sqlQuery(sqlStr);
      //结果返回
  return Array.from(result);

}

async function getType(){
  let sqlStr1 = 'select * from type where state = 1'
  let result1 = await sqlQuery(sqlStr1);
      //结果返回
  return Array.from(result1);

}

module.exports = router;